<template>
  <div class="circuit-diagram-draw">
    <!-- 顶部工具栏 -->
    <div class="toolbar" v-if="!isViewMode">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleSave">
          <el-icon><Save /></el-icon>
          保存
        </el-button>
        <el-button @click="handleDownload">
          <el-icon><Download /></el-icon>
          下载图片
        </el-button>
        <el-button @click="handleClear">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
      </div>
      
      <div class="toolbar-center">
        <el-button 
          :type="isLineMode ? 'primary' : 'default'"
          @click="toggleLineMode"
        >
          <el-icon><Connection /></el-icon>
          {{ isLineMode ? '退出连线' : '连线编辑' }}
        </el-button>
        <el-button 
          :type="showEffectPanel ? 'primary' : 'default'"
          @click="toggleEffectPanel"
        >
          <el-icon><Magic /></el-icon>
          连线特效
        </el-button>
      </div>
      
      <div class="toolbar-right">
        <el-color-picker 
          v-model="backgroundColor" 
          @change="handleBackgroundColorChange"
          show-alpha
        />
        <span class="color-label">背景色</span>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content" :class="{ 'view-mode': isViewMode }">
      <!-- 左侧设备图区域 -->
      <div class="left-panel" v-if="!isViewMode">
        <div class="panel-header">
          <h3>设备图</h3>
        </div>
        <div class="device-groups">
          <div 
            v-for="group in deviceGroups" 
            :key="group.id" 
            class="device-group"
          >
            <div class="group-header">
              <h4>{{ group.groupName }}</h4>
            </div>
            <div class="device-list">
              <div
                v-for="device in group.deviceImages"
                :key="device.id"
                class="device-item"
                draggable="true"
                @dragstart="handleDragStart($event, device)"
              >
                <img :src="device.imageUrl" :alt="device.imageName" />
                <span class="device-name">{{ device.imageName }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 连线特效设置面板 -->
        <LineEffectPanel
          v-if="showEffectPanel"
          v-model="currentLineEffect"
          @apply-to-selected="applyEffectToSelected"
          @line-color-change="applyLineColorToSelected"
          @line-width-change="applyLineWidthToSelected"
        />
      </div>

      <!-- 右侧绘制区域 -->
      <div class="right-panel">
        <div class="drawing-area" 
          ref="drawingAreaRef"
          :style="{ backgroundColor: backgroundColor }"
          @drop="handleDrop"
          @dragover="handleDragOver"
          @click="handleCanvasClick"
          @mousedown="handleCanvasMouseDown"
          @mousemove="handleCanvasMouseMove"
          @mouseup="handleCanvasMouseUp"
        >
          <!-- 绘制的设备图 -->
          <div
            v-for="element in diagramElements"
            :key="element.id"
            class="diagram-element"
            :class="[
              element.type,
              { 
                'selected': selectedElement?.id === element.id,
                'hovered': hoveredElement?.id === element.id,
                'dragging': isDraggingElement && draggingElement?.id === element.id
              }
            ]"
            :style="getElementStyle(element)"
            @dblclick="handleElementDoubleClick(element)"
            @mousedown="handleElementMouseDown($event, element)"
            @mouseenter="handleElementMouseEnter(element)"
            @mouseleave="handleElementMouseLeave(element)"
            @click="handleElementClick($event, element)"
          >
            <!-- 设备图 -->
            <template v-if="element.type === 'device'">
              <img 
                v-if="element.imageUrl" 
                :src="element.imageUrl" 
                :alt="element.deviceName"
                :style="{ filter: element.deviceColor ? `hue-rotate(${getHueRotation(element.deviceColor)})` : '' }"
              />
              <div v-if="element.deviceName" class="device-label">
                {{ element.deviceName }}
              </div>
              
              <!-- 选择状态下的连接点 -->
              <div 
                v-if="selectedElement?.id === element.id && isLineMode"
                class="connection-points"
              >
                <div 
                  v-for="(point, index) in getConnectionPoints(element)"
                  :key="index"
                  class="connection-point"
                  :class="{ 'hovered': hoveredConnectionPoint === index }"
                  :style="getConnectionPointStyle(element, point)"
                  @mousedown.stop="handleConnectionPointMouseDown($event, element, point, index)"
                  @mouseenter="hoveredConnectionPoint = index"
                  @mouseleave="hoveredConnectionPoint = null"
                ></div>
              </div>
              
              <!-- 选择状态下的边框 -->
              <div 
                v-if="selectedElement?.id === element.id"
                class="selection-border"
              ></div>
            </template>
          </div>
          
          <!-- 连线元素 -->
          <div
            v-for="element in lineElements"
            :key="element.id"
            class="line-element"
            :class="{ 'selected': selectedElement?.id === element.id }"
            @click="handleElementClick($event, element)"
          >
            <AnimatedLine
              :start-point="element.startPoint!"
              :end-point="element.endPoint!"
              :line-color="element.lineColor || '#000'"
              :line-width="element.lineWidth || 2"
              :effect="element.lineEffect"
              :line-label="element.lineLabel"
              :element-id="element.id"
            />
            
            <!-- 连线选择状态下的边框 -->
            <div 
              v-if="selectedElement?.id === element.id"
              class="line-selection-border"
              :style="getLineSelectionBorderStyle(element)"
            ></div>
          </div>
          
          <!-- 正在绘制的连线 -->
          <svg v-if="isDrawingLine" class="drawing-line-svg">
            <line
              :x1="drawingLine.start.x"
              :y1="drawingLine.start.y"
              :x2="drawingLine.end.x"
              :y2="drawingLine.end.y"
              stroke="#666"
              stroke-width="2"
              stroke-dasharray="5,5"
            />
          </svg>
        </div>
      </div>
    </div>

    <!-- 设备名称编辑对话框 -->
    <el-dialog
      v-model="deviceNameDialog.visible"
      title="编辑设备名称"
      width="400px"
    >
      <el-form>
        <el-form-item label="设备名称">
          <el-input
            v-model="deviceNameDialog.name"
            placeholder="请输入设备名称"
            @keyup.enter="handleDeviceNameConfirm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deviceNameDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleDeviceNameConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设备颜色选择对话框 -->
    <el-dialog
      v-model="deviceColorDialog.visible"
      title="选择设备颜色"
      width="400px"
    >
      <el-color-picker
        v-model="deviceColorDialog.color"
        show-alpha
        @change="handleDeviceColorChange"
      />
      <template #footer>
        <el-button @click="deviceColorDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleDeviceColorConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 连线标签编辑对话框 -->
    <el-dialog
      v-model="lineLabelDialog.visible"
      title="编辑连线标签"
      width="400px"
    >
      <el-form>
        <el-form-item label="连线标签">
          <el-input
            v-model="lineLabelDialog.label"
            placeholder="请输入连线标签"
            @keyup.enter="handleLineLabelConfirm"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="lineLabelDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleLineLabelConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { v4 as uuidv4 } from 'uuid'
import html2canvas from 'html2canvas'
import { circuitDiagramApi } from '@/api/circuitDiagram'
import { deviceGroupApi } from '@/api/deviceGroup'
import type { CircuitDiagramVO, DeviceGroupVO, DeviceImageVO, DiagramElement, LineEffect } from '@/types/circuitDiagram'
import LineEffectPanel from '@/components/LineEffectPanel.vue'
import AnimatedLine from '@/components/AnimatedLine.vue'

// 路由实例
const route = useRoute()
const router = useRouter()

// 响应式数据
const drawingAreaRef = ref<HTMLElement>()
const isViewMode = computed(() => route.query.mode === 'view')
const isLineMode = ref(false)
const showEffectPanel = ref(false)
const backgroundColor = ref('#ffffff')
const diagramName = ref('未命名一次图')
const deviceGroups = ref<DeviceGroupVO[]>([])
const diagramElements = ref<DiagramElement[]>([])
const hoveredElement = ref<DiagramElement | null>(null)
const selectedElement = ref<DiagramElement | null>(null)
const hoveredConnectionPoint = ref<number | null>(null)
const isDrawingLine = ref(false)
const drawingLine = reactive({
  start: { x: 0, y: 0 },
  end: { x: 0, y: 0 }
})

// 连线绘制相关状态
const isDrawingFromCanvas = ref(false)
const drawingStartPoint = ref<{ x: number; y: number } | null>(null)

// 当前连线特效配置
const currentLineEffect = ref<LineEffect>({
  type: 'current',
  enabled: true,
  color: '#409eff',
  speed: 1000,
  size: 3,
  direction: 'forward',
  intensity: 1,
  opacity: 0.8
})

// 对话框数据
const deviceNameDialog = reactive({
  visible: false,
  name: '',
  element: null as DiagramElement | null
})

const deviceColorDialog = reactive({
  visible: false,
  color: '#000000',
  element: null as DiagramElement | null
})

const lineLabelDialog = reactive({
  visible: false,
  label: '',
  element: null as DiagramElement | null
})

// 计算属性：连线元素
const lineElements = computed(() => {
  return diagramElements.value.filter(element => element.type === 'line')
})

// 拖拽移动相关状态
const isDraggingElement = ref(false)
const draggingElement = ref<DiagramElement | null>(null)
const dragStartPos = reactive({ x: 0, y: 0 })

// 获取设备分组数据
const getDeviceGroups = async () => {
  try {
    const res = await deviceGroupApi.getAllGroupsWithImages()
    if (res.code === 200) {
      deviceGroups.value = res.data
    } else {
      // 使用模拟数据
      deviceGroups.value = [
        {
          id: 1,
          groupName: '默认分组',
          sortOrder: 1,
          createTime: '2024-01-01 00:00:00',
          createBy: 'system',
          deviceImages: []
        }
      ]
    }
  } catch (error) {
    console.error('获取设备分组失败:', error)
    ElMessage.error(`获取设备分组失败: ${error}`)
    // 使用模拟数据
    deviceGroups.value = [
      {
        id: 1,
        groupName: '默认分组',
        sortOrder: 1,
        createTime: '2024-01-01 00:00:00',
        createBy: 'system',
        deviceImages: []
      }
    ]
  }
}

// 拖拽开始
const handleDragStart = (event: DragEvent, device: DeviceImageVO) => {
  if (event.dataTransfer) {
    // 确保设备对象包含必要的属性
    const dragData = {
      id: device.id,
      imageUrl: device.imageUrl,
      imageName: device.imageName,
      fileName: device.fileName,
      groupId: device.groupId,
      groupName: device.groupName
    }
    
    // 设置拖拽数据
    event.dataTransfer.setData('text/plain', JSON.stringify(dragData))
    
    // 设置拖拽图像（可选）
    if (device.imageUrl) {
      const img = new Image()
      img.src = device.imageUrl
      img.onload = () => {
        event.dataTransfer?.setDragImage(img, 40, 40)
      }
    }
    
    console.log('开始拖拽设备:', dragData)
  }
}

// 拖拽悬停
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  
  // 如果正在拖拽移动设备图，不显示拖拽提示
  if (isDraggingElement.value) return
}

// 拖拽放置
const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  
  // 如果正在拖拽移动设备图，不处理从左侧拖拽的设备图
  if (isDraggingElement.value) return
  
  if (!event.dataTransfer) return
  
  const deviceData = event.dataTransfer.getData('text/plain')
  if (!deviceData) return
  
  try {
    let device: any
    
    // 尝试解析为JSON对象
    try {
      device = JSON.parse(deviceData)
    } catch (parseError) {
      // 如果解析失败，可能是URL，创建一个基本的设备对象
      console.warn('设备数据解析失败，使用URL作为图片地址:', deviceData)
      
      // 检查是否是有效的URL
      if (deviceData.startsWith('http') || deviceData.startsWith('/')) {
        device = {
          id: uuidv4(),
          imageUrl: deviceData,
          imageName: '设备图',
          fileName: 'device.svg',
          groupId: 'default',
          groupName: '默认分组'
        }
      } else {
        throw new Error('无效的设备数据格式')
      }
    }
    
    // 验证设备数据的必要属性
    if (!device.imageUrl) {
      throw new Error('设备图片URL不能为空')
    }
    
    const rect = drawingAreaRef.value?.getBoundingClientRect()
    if (!rect) return
    
    const x = event.clientX - rect.left
    const y = event.clientY - rect.top
    
    // 创建设备元素
    const element: DiagramElement = {
      id: uuidv4(),
      type: 'device',
      x,
      y,
      width: 80,
      height: 80,
      imageUrl: device.imageUrl,
      deviceName: device.imageName || '设备图',
      deviceColor: '#000000'
    }
    
    diagramElements.value.push(element)
    
    // 放置后自动进入选择模式
    nextTick(() => {
      selectedElement.value = element
    })
    
    console.log('设备图放置成功:', element)
    ElMessage.success('设备图放置成功')
  } catch (error) {
    console.error('处理设备数据失败:', error)
    ElMessage.error(`设备图放置失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 切换连线模式
const toggleLineMode = () => {
  isLineMode.value = !isLineMode.value
  // 退出连线模式时清除选中状态
  if (!isLineMode.value) {
    selectedElement.value = null
  }
}

// 切换特效面板
const toggleEffectPanel = () => {
  showEffectPanel.value = !showEffectPanel.value
}

// 获取元素样式
const getElementStyle = (element: DiagramElement) => {
  if (element.type === 'device') {
    return {
      left: `${element.x}px`,
      top: `${element.y}px`,
      width: `${element.width}px`,
      height: `${element.height}px`
    }
  }
  return {}
}

// 获取连接点
const getConnectionPoints = (element: DiagramElement) => {
  if (element.type !== 'device' || !element.width || !element.height) return []
  
  const points = []
  const width = element.width
  const height = element.height
  
  // 四个边的中点
  points.push({ x: width / 2, y: 0 }) // 上
  points.push({ x: width, y: height / 2 }) // 右
  points.push({ x: width / 2, y: height }) // 下
  points.push({ x: 0, y: height / 2 }) // 左
  
  return points
}

// 获取连接点样式
const getConnectionPointStyle = (element: DiagramElement, point: { x: number; y: number }) => {
  return {
    left: `${point.x - 6}px`,
    top: `${point.y - 6}px`,
    width: '12px',
    height: '12px'
  }
}

// 连接点鼠标按下
const handleConnectionPointMouseDown = (event: MouseEvent, element: DiagramElement, point: { x: number; y: number }, pointIndex: number) => {
  if (!isLineMode.value) return
  
  event.stopPropagation()
  isDrawingLine.value = true
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  drawingLine.start = {
    x: element.x + point.x,
    y: element.y + point.y
  }
  drawingLine.end = {
    x: element.x + point.x,
    y: element.y + point.y
  }
  
  const handleMouseMove = (e: MouseEvent) => {
    drawingLine.end = {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    }
  }
  
  const handleMouseUp = (e: MouseEvent) => {
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    
    isDrawingLine.value = false
    
    // 检查是否连接到其他连接点
    const targetElement = findElementAtPosition(e.clientX - rect.left, e.clientY - rect.top)
    if (targetElement && targetElement.type === 'device' && targetElement.id !== element.id) {
      const targetPoints = getConnectionPoints(targetElement)
      const targetPoint = findNearestConnectionPoint(targetElement, e.clientX - rect.left, e.clientY - rect.top, targetPoints)
      
      if (targetPoint) {
        drawingLine.end = {
          x: targetElement.x + targetPoint.x,
          y: targetElement.y + targetPoint.y
        }
      }
    }
    
    // 创建连线元素
    const lineElement: DiagramElement = {
      id: uuidv4(),
      type: 'line',
      x: 0,
      y: 0,
      startPoint: { ...drawingLine.start },
      endPoint: { ...drawingLine.end },
      lineColor: '#000000',
      lineWidth: 2,
      lineEffect: { ...currentLineEffect.value }
    }
    
    diagramElements.value.push(lineElement)
    
    // 连线创建后自动选中
    selectedElement.value = lineElement
  }
  
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 查找指定位置的元素
const findElementAtPosition = (x: number, y: number): DiagramElement | null => {
  // 首先检查连线元素（连线需要优先检测）
  for (const element of lineElements.value) {
    if (element.startPoint && element.endPoint) {
      if (isPointNearLine(x, y, element.startPoint, element.endPoint, 5)) {
        return element
      }
    }
  }
  
  // 然后检查设备元素
  for (const element of diagramElements.value) {
    if (element.type === 'device' && element.width && element.height) {
      if (x >= element.x && x <= element.x + element.width &&
          y >= element.y && y <= element.y + element.height) {
        return element
      }
    }
  }
  return null
}

// 检查点是否在线段附近
const isPointNearLine = (px: number, py: number, start: { x: number; y: number }, end: { x: number; y: number }, threshold: number): boolean => {
  const A = px - start.x
  const B = py - start.y
  const C = end.x - start.x
  const D = end.y - start.y

  const dot = A * C + B * D
  const lenSq = C * C + D * D
  
  if (lenSq === 0) return false
  
  let param = dot / lenSq

  let xx, yy

  if (param < 0) {
    xx = start.x
    yy = start.y
  } else if (param > 1) {
    xx = end.x
    yy = end.y
  } else {
    xx = start.x + param * C
    yy = start.y + param * D
  }

  const dx = px - xx
  const dy = py - yy
  const distance = Math.sqrt(dx * dx + dy * dy)

  return distance <= threshold
}

// 查找最近的连接点
const findNearestConnectionPoint = (element: DiagramElement, x: number, y: number, points: { x: number; y: number }[]) => {
  let nearestPoint = null
  let minDistance = Infinity
  
  for (const point of points) {
    const distance = Math.sqrt(
      Math.pow(x - (element.x + point.x), 2) + 
      Math.pow(y - (element.y + point.y), 2)
    )
    if (distance < minDistance && distance < 20) { // 20px 吸附范围
      minDistance = distance
      nearestPoint = point
    }
  }
  
  return nearestPoint
}

// 元素鼠标进入
const handleElementMouseEnter = (element: DiagramElement) => {
  if (isLineMode.value && element.type === 'device') {
    hoveredElement.value = element
  }
}

// 元素鼠标离开
const handleElementMouseLeave = () => {
  hoveredElement.value = null
}

// 元素点击
const handleElementClick = (event: MouseEvent, element: DiagramElement) => {
  // 阻止事件冒泡，避免触发画布点击事件
  event.stopPropagation()
  
  // 如果点击的是当前选中的元素，不做任何操作
  if (selectedElement.value?.id === element.id) {
    return
  }
  
  // 选中新元素
  selectedElement.value = element
  
  // 如果是设备图，可以在这里添加一些反馈
  if (element.type === 'device') {
    console.log('设备图已选中:', element.deviceName || element.id)
  } else if (element.type === 'line') {
    console.log('连线已选中:', element.id)
  }
}

// 元素双击
const handleElementDoubleClick = (element: DiagramElement) => {
  if (element.type === 'device') {
    deviceNameDialog.element = element
    deviceNameDialog.name = element.deviceName || ''
    deviceNameDialog.visible = true
  } else if (element.type === 'line') {
    lineLabelDialog.element = element
    lineLabelDialog.label = element.lineLabel || ''
    lineLabelDialog.visible = true
  }
}

// 画布点击
const handleCanvasClick = (event: MouseEvent) => {
  // 检查是否点击在元素上
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  const clickedElement = findElementAtPosition(x, y)
  
  // 如果没有点击在元素上，才清除选中状态
  if (!clickedElement) {
    selectedElement.value = null
  }
}

// 画布鼠标按下
const handleCanvasMouseDown = (event: MouseEvent) => {
  // 如果正在拖拽元素，不处理画布拖拽
  if (isDraggingElement.value) return
  
  if (!isLineMode.value) return
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  // 检查是否点击在元素上
  const clickedElement = findElementAtPosition(x, y)
  if (clickedElement) {
    return // 如果点击在元素上，不处理画布拖拽
  }
  
  // 开始从画布拖拽连线
  isDrawingFromCanvas.value = true
  drawingStartPoint.value = { x, y }
  isDrawingLine.value = true
  
  drawingLine.start = { x, y }
  drawingLine.end = { x, y }
}

// 画布鼠标移动
const handleCanvasMouseMove = (event: MouseEvent) => {
  // 如果正在拖拽元素，不处理画布移动
  if (isDraggingElement.value) return
  
  if (!isDrawingFromCanvas.value || !isLineMode.value) return
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  drawingLine.end = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  }
}

// 画布鼠标抬起
const handleCanvasMouseUp = (event: MouseEvent) => {
  // 如果正在拖拽元素，不处理画布抬起
  if (isDraggingElement.value) return
  
  if (!isDrawingFromCanvas.value || !isLineMode.value) return
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  isDrawingFromCanvas.value = false
  isDrawingLine.value = false
  
  const endX = event.clientX - rect.left
  const endY = event.clientY - rect.top
  
  // 检查是否连接到设备
  const targetElement = findElementAtPosition(endX, endY)
  if (targetElement && targetElement.type === 'device') {
    const targetPoints = getConnectionPoints(targetElement)
    const targetPoint = findNearestConnectionPoint(targetElement, endX, endY, targetPoints)
    
    if (targetPoint) {
      drawingLine.end = {
        x: targetElement.x + targetPoint.x,
        y: targetElement.y + targetPoint.y
      }
    }
  }
  
  // 创建连线元素
  const lineElement: DiagramElement = {
    id: uuidv4(),
    type: 'line',
    x: 0,
    y: 0,
    startPoint: { ...drawingLine.start },
    endPoint: { ...drawingLine.end },
    lineColor: '#000000',
    lineWidth: 2,
    lineEffect: { ...currentLineEffect.value }
  }
  
  diagramElements.value.push(lineElement)
  
  // 连线创建后自动选中
  selectedElement.value = lineElement
}

// 获取连线选择边框样式
const getLineSelectionBorderStyle = (element: DiagramElement) => {
  if (element.type !== 'line' || !element.startPoint || !element.endPoint) return {}
  
  const minX = Math.min(element.startPoint.x, element.endPoint.x)
  const minY = Math.min(element.startPoint.y, element.endPoint.y)
  const maxX = Math.max(element.startPoint.x, element.endPoint.x)
  const maxY = Math.max(element.startPoint.y, element.endPoint.y)
  
  return {
    left: `${minX - 5}px`,
    top: `${minY - 5}px`,
    width: `${maxX - minX + 10}px`,
    height: `${maxY - minY + 10}px`
  }
}

// 确认设备名称
const handleDeviceNameConfirm = () => {
  if (deviceNameDialog.element) {
    deviceNameDialog.element.deviceName = deviceNameDialog.name
    deviceNameDialog.visible = false
  }
}

// 设备颜色改变
const handleDeviceColorChange = (color: string) => {
  deviceColorDialog.color = color
}

// 确认设备颜色
const handleDeviceColorConfirm = () => {
  if (deviceColorDialog.element) {
    deviceColorDialog.element.deviceColor = deviceColorDialog.color
    deviceColorDialog.visible = false
  }
}

// 确认连线标签
const handleLineLabelConfirm = () => {
  if (lineLabelDialog.element) {
    lineLabelDialog.element.lineLabel = lineLabelDialog.label
    lineLabelDialog.visible = false
  }
}

// 应用特效到选中连线
const applyEffectToSelected = (effect: LineEffect) => {
  if (selectedElement.value && selectedElement.value.type === 'line') {
    selectedElement.value.lineEffect = { ...effect }
    ElMessage.success('特效已应用到选中连线')
  } else {
    ElMessage.warning('请先选择一条连线')
  }
}

// 应用连线颜色到选中连线
const applyLineColorToSelected = (color: string) => {
  if (selectedElement.value && selectedElement.value.type === 'line') {
    selectedElement.value.lineColor = color
    ElMessage.success('连线颜色已更新')
  } else {
    ElMessage.warning('请先选择一条连线')
  }
}

// 应用连线宽度到选中连线
const applyLineWidthToSelected = (width: number) => {
  if (selectedElement.value && selectedElement.value.type === 'line') {
    selectedElement.value.lineWidth = width
    ElMessage.success('连线宽度已更新')
  } else {
    ElMessage.warning('请先选择一条连线')
  }
}

// 获取色相旋转角度
const getHueRotation = (color: string) => {
  // 这里应该实现颜色转换逻辑
  // 简化实现，实际应该根据颜色计算色相旋转角度
  return '0deg'
}

// 背景色改变
const handleBackgroundColorChange = (color: string) => {
  backgroundColor.value = color
}

// 元素鼠标按下
const handleElementMouseDown = (event: MouseEvent, element: DiagramElement) => {
  // 如果是连线模式，不处理拖拽
  if (isLineMode.value) return
  
  // 阻止事件冒泡
  event.stopPropagation()
  
  // 选中元素
  selectedElement.value = element
  
  // 开始拖拽
  isDraggingElement.value = true
  draggingElement.value = element
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  // 记录拖拽开始位置
  dragStartPos.x = event.clientX - rect.left
  dragStartPos.y = event.clientY - rect.top
  
  // 添加全局鼠标事件监听
  document.addEventListener('mouseup', handleElementDragEnd)
  
  console.log('开始拖拽设备图:', element.id)
}

// 元素拖拽结束
const handleElementDragEnd = (event: MouseEvent) => {
  if (!isDraggingElement.value || !draggingElement.value) return
  
  const rect = drawingAreaRef.value?.getBoundingClientRect()
  if (!rect) return
  
  // 计算鼠标当前位置
  const mouseX = event.clientX - rect.left
  const mouseY = event.clientY - rect.top
  
  console.log('拖拽结束前状态:', {
    isDragging: isDraggingElement.value,
    draggingElementId: draggingElement.value.id,
    newPosition: { x: mouseX, y: mouseY }
  })
  
  // 直接移动设备图到鼠标位置
  draggingElement.value.x = Math.max(0, mouseX - (draggingElement.value.width || 80) / 2)
  draggingElement.value.y = Math.max(0, mouseY - (draggingElement.value.height || 80) / 2)
  
  // 立即重置拖拽状态
  isDraggingElement.value = false
  const movedElement = draggingElement.value
  draggingElement.value = null
  
  // 移除全局事件监听
  document.removeEventListener('mouseup', handleElementDragEnd)
  
  // 强制触发响应式更新
  diagramElements.value = [...diagramElements.value]
  
  // 确保移动后的元素保持选中状态
  nextTick(() => {
    selectedElement.value = movedElement
  })
  
  console.log('拖拽结束，设备图已移动到新位置，虚化效果已清除')
  console.log('拖拽结束后状态:', {
    isDragging: isDraggingElement.value,
    draggingElement: draggingElement.value,
    selectedElement: selectedElement.value?.id
  })
}

// 保存
const handleSave = async () => {
  try {
    const data = {
      name: diagramName.value || '未命名一次图',
      diagramJson: JSON.stringify({
        elements: diagramElements.value,
        backgroundColor: backgroundColor.value
      }),
      operator: 'admin'
    }
    
    const res = await circuitDiagramApi.save(data)
    if (res.code === 200) {
      ElMessage.success('保存成功')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error}`)
  }
}

// 下载图片
const handleDownload = async () => {
  if (!drawingAreaRef.value) return
  
  try {
    const canvas = await html2canvas(drawingAreaRef.value)
    const link = document.createElement('a')
    link.download = '一次图.png'
    link.href = canvas.toDataURL()
    link.click()
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`下载失败: ${error}`)
  }
}

// 清空
const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空当前绘制的内容吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    diagramElements.value = []
    selectedElement.value = null
    ElMessage.success('清空成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      ElMessage.error(`清空失败: ${error}`)
    }
  }
}

// 加载一次图数据
const loadDiagramData = async (id: string) => {
  try {
    const res = await circuitDiagramApi.getDetail(id)
    if (res.code === 200 && res.data) {
      const diagramData = JSON.parse(res.data.diagramJson)
      diagramElements.value = diagramData.elements || []
      backgroundColor.value = diagramData.backgroundColor || '#ffffff'
    }
  } catch (error) {
    console.error('加载一次图数据失败:', error)
    ElMessage.error(`加载一次图数据失败: ${error}`)
  }
}

// 页面加载
onMounted(async () => {
  await getDeviceGroups()
  
  // 如果是编辑或查看模式，加载数据
  const id = route.query.id as string
  if (id) {
    await loadDiagramData(id)
  }
})
</script>

<style scoped>
.circuit-diagram-draw {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: #fff;
  border-bottom: 1px solid #dcdfe6;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-left,
.toolbar-center,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.color-label {
  font-size: 14px;
  color: #606266;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.main-content.view-mode {
  flex-direction: column;
}

.left-panel {
  width: 350px;
  background: #fff;
  border-right: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #dcdfe6;
}

.panel-header h3 {
  margin: 0;
  color: #303133;
}

.device-groups {
  flex: 1;
  padding: 10px;
}

.device-group {
  margin-bottom: 20px;
}

.group-header h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.device-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.device-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: grab;
  transition: all 0.3s;
}

.device-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.device-item img {
  width: 40px;
  height: 40px;
  margin-bottom: 5px;
}

.device-name {
  font-size: 12px;
  color: #606266;
  text-align: center;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.drawing-area {
  flex: 1;
  position: relative;
  overflow: auto;
  background: #f5f7fa;
  cursor: crosshair;
}

.diagram-element {
  position: absolute;
  cursor: pointer;
  transition: all 0.2s ease;
}

.diagram-element.device {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.diagram-element.device img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.device-label {
  position: absolute;
  top: -25px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  white-space: nowrap;
}

/* 选择状态样式 */
.diagram-element.selected {
  z-index: 10;
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.diagram-element.selected .selection-border {
  position: absolute;
  top: -4px;
  left: -4px;
  right: -4px;
  bottom: -4px;
  border: 2px solid #409eff;
  border-radius: 4px;
  pointer-events: none;
  animation: selectionPulse 2s infinite;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 设备图选中时的特殊样式 */
.diagram-element.device.selected {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
}

.diagram-element.device.selected img {
  filter: brightness(1.1) contrast(1.1);
}

/* 拖拽状态样式 - 虚化效果 */
.diagram-element.dragging {
  opacity: 0.3;
  filter: blur(1px);
  transform: scale(0.95);
  transition: all 0.1s ease;
}

.diagram-element.dragging img {
  filter: brightness(0.8) contrast(0.8);
}

/* 拖拽时的连接点隐藏 */
.diagram-element.dragging .connection-points {
  display: none;
}

/* 拖拽状态重置时的样式 - 立即生效 */
.diagram-element:not(.dragging) {
  opacity: 1;
  filter: none;
  transform: none;
  transition: none;
}

.diagram-element:not(.dragging) img {
  filter: none;
}

.connection-points {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.connection-point {
  position: absolute;
  background: #409eff;
  border: 2px solid white;
  border-radius: 50%;
  pointer-events: all;
  cursor: crosshair;
  z-index: 20;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.connection-point:hover {
  background: #66b1ff;
  transform: scale(1.2);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.connection-point.hovered {
  background: #66b1ff;
  transform: scale(1.2);
}

.line-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.line-element.selected {
  pointer-events: all;
}

.line-selection-border {
  position: absolute;
  border: 2px dashed #409eff;
  border-radius: 4px;
  pointer-events: none;
  animation: selectionPulse 2s infinite;
}

.drawing-line-svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1000;
}

/* 连线模式下的画布样式 */
.drawing-area.line-mode {
  cursor: crosshair;
}

/* 设备图悬停效果 */
.diagram-element.device:hover {
  transform: scale(1.05);
}

/* 连线悬停效果 */
.line-element:hover {
  pointer-events: all;
}
</style> 